import React, { useState, useEffect } from 'react'
import { Input } from 'antd'
import '@/styles/Weather.scss'
import weatherIcon from './WeatherFn'
import JsonP from 'jsonp'
import { Card, Col, Row } from 'antd';
import ReactEcharts from 'echarts-for-react'



export default function LocationWeather() {

  const [value,setvalue] = useState()

  const [dataDay,setdataDay] = useState()
  const [iconfont,seticonfont] = useState()

  const [TodayWeather,setTodayWeather] = useState()
  const [InWeather,setInWeather] = useState([{},{},{},{}])

  const [IcondOption,setIcondOption] = useState({})
  const [IconnOption,setIconnOption] = useState({})

  // const [currentCity,setCurrentCity] = useState()

  const handleWeather = (value = localStorage.getItem('currentCity'))=> {

    JsonP(`https://api.asilu.com/weather/?city=${value}`,{},function(err,data){
      setdataDay(data.date)
      seticonfont(data.city)
      localStorage.setItem('currentCity',value)

      setTodayWeather(data.weather['0'])
      setInWeather(data.weather)
    
      let arr1 = []; 
      let arr2 = [];
      InWeather?.forEach(
          (item,index)=>{arr1[index] = Number(item.icond);arr2[index] = Number(item.iconn)}
        )
      // console.log(arr2);
      // setOptionIcond('PM2.5',arr1,'bar')
      // setOptionIconn('湿度',arr2,'line')
    })
  }

  const handleWeather2 = ()=>{
    JsonP(`https://api.asilu.com/weather/?city=${value}`,{},function(err,data){
      setInWeather(data.weather)
    
      let arr1 = []; 
      let arr2 = [];
      InWeather?.forEach(
          (item,index)=>{arr1[index] = Number(item.icond);arr2[index] = Number(item.iconn)}
        )
      // console.log(arr2);
      setOptionIcond('PM2.5',arr1,'bar')
      setOptionIconn('湿度',arr2,'line')
    })
  }

  useEffect(()=>{
    handleWeather()
  // eslint-disable-next-line react-hooks/exhaustive-deps
  },[value])

  // PM2.5的图表函数
  const setOptionIcond = (text,data,type='bar')=>{
    let IcondOption =  {
      title: {
        text,
        backgroundColor:'#ccccd6',
        borderRadius: [5, 5, 0, 0]
      },
      grid:{ 
        top:'24%',
        bottom:'3%',
        containLabel:true
      },
      tooltip: {
        valueFormatter: (value) => '^_^:' + value,
        textStyle:{
          color:'#ccccd6'
        }
      },
      legend:{
        data:[
          {
            name:'PM2.5',
            icon: 'circle',
          },
        ],
        textStyle: { 
          color: '#ccccd6'
        },
        itemWidth:10,
        itemHeight:10,
        itemGap:12
      },
      xAxis: {
        data: InWeather?.map((item)=>{const arr = []; arr.push(item?.date?.slice(0,3));return arr}),
        axisLabel: {
          interval: 0, 
          rotate: '45',
        },
      },
      yAxis: {
        name: "数据", 
        nameRotate: 50,
        splitNumber: 8, 
        axisLine: {  
          show: true,
          lineStyle: {
            width:1,
            color: "#ccccd6"
          }
        }
      },
      series: [
        {
          name: 'PM2.5',
          type,
          data,
          barWidth: 12, 
          itemStyle:{ 
            color:'#ccccd6'
          },
          markPoint: { 
            data: [{
              type: "max"
            }],
            symbol: "pin"
          },
          markLine: { 
            data: [{
              type: "average"
            }],
            silent: true
          }
        },
      ]
    }
    setIcondOption(IcondOption)
  }

  // 湿度的图表函数
  const setOptionIconn = (text,data,type='bar')=>{
    let IconnOption =  {
      title: {
        text,
        backgroundColor:'#93b5cf',
        borderRadius: [5, 5, 0, 0]
      },
      grid:{ 
        top:'24%',
        bottom:'3%',
        containLabel:true
      },
      tooltip: {
        valueFormatter: (value) => '^_^:' + value,
        textStyle:{
          color:'#93b5cf'
        }
      },
      legend:{
        data:[
          {
            name:'湿度',
            icon: 'circle',
          },
        ],
        textStyle: { 
          color: '#93b5cf'
        },
        itemWidth:10,
        itemHeight:10,
        itemGap:12
      },
      xAxis: {
        data: InWeather?.map((item)=>{const arr = []; arr.push(item?.date?.slice(0,3));return arr}),
        axisLabel: {
          interval: 0, 
          rotate: '45',
        },
      },
      yAxis: {
        name: "数据", 
        nameRotate: 50,
        splitNumber: 8, 
        axisLine: {  
          show: true,
          lineStyle: {
            width:1,
            color: "#93b5cf"
          }
        }
      },
      series: [
        {
          name: '湿度',
          type,
          data,
          barWidth: 12, 
          itemStyle:{
            color:'#93b5cf'
          },
          markPoint: {
            data: [{
              type: "max"
            }],
            symbol: "pin"
          },
          markLine: { 
            data: [{
              type: "average"
            }],
            silent: true
          }
        },
      ]
    }
    setIconnOption(IconnOption)
  }


  return (
    <>
      {/* 天气搜索界面 */}
      <div className='container'>   
        <div className="weather-side">
          <div className="gradient"></div>
          <div className="date-container">
            <h2 className="date-dayname">{TodayWeather?.data}</h2>
            <span className="date-day">{dataDay}</span>
            <span className="iconfont">&#xe617;{iconfont}</span>
          </div>
          <div className="weather-conteiner">
            <span className="iconfont weather-l">&#xe61f;</span>
            <div className="weather-temp">{TodayWeather?.temp}</div>
            <div className="weather-desc">{TodayWeather?.weather}</div>
          </div>
        </div>
        <div className="info-side">
          <div className="today-info-container">
            <div className="today-info">
              <div className="pm clear">
                <span className="title">PM2.5</span>
                <span className="value pm">{TodayWeather?.icond}</span>
              </div>
              <div className="humidity clear">
                <span className="title">湿度</span>
                <span className="value humidity">{TodayWeather?.iconn}</span>
              </div>
              <div className="wind clear">
                <span className="title">风速</span>
                <span className="value wind">{TodayWeather?.w}</span>
              </div>
            </div>
          </div>
          <div className="week-container">
            <ul className="week-list">
              {
                InWeather?.slice(0,4)?.map((item,key)=>{
                  const weatherIconItem = weatherIcon(item?.weather || '大')
                  return (
                    <li className="active day1" key={key}>
                      <span className="iconfont">{weatherIconItem}</span>
                      <span className="day-name">{item.weather}</span>
                      <span className="day-temp">{item.temp}</span>
                    </li>)
                }) 
              }
            </ul>
          </div>
          <div className="location-container">
            <Input placeholder="位置" value={value} onChange={(e)=>{setvalue(e.target.value)}}/>
            <button className="location-button" onClick={()=>handleWeather(value)}>
              <span className="iconfont">&#xe617;查询</span>
            </button>
          </div>
        </div>
      </div>
      <button className="echarts-button" onClick={()=>handleWeather2(value)}>生成图表</button>

      {/* echarts图形 */}
      <Row 
        gutter={16} 
        style={{
            display:'fixed',
            justifyContent:"space-around",
            height:"300px",
            marginTop:'20px'
          }}
        >
        <Col span={9} style={{height:"100%"}}>
          <Card title="PM2.5图例" bordered={false} style={{height:"100%"}}>
            <ReactEcharts
              option={IcondOption}
              style={{height:'200px'}}
            />
          </Card>
        </Col>
        <Col span={9} style={{height:"100%"}}>
          <Card title="湿度图例" bordered={false} style={{height:"100%"}}>
            <ReactEcharts
              option={IconnOption}
              style={{height:'200px'}}
            />
          </Card>
        </Col>
      </Row>
    </>
  )
}
